﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChatRoomListPanel : MonoBehaviour
{
    public Transform RoomParent;
    public GameObject RoomPrefab;

    private Queue<string> addRooms = new Queue<string>();
    private Queue<string> rmRooms = new Queue<string>();
    private Queue<string> modifyRooms = new Queue<string>();

    private void Awake()
    {
        Singleton<RoomManager>.GetInstance().OnKeyAdd += OnRoomAdd;
        Singleton<RoomManager>.GetInstance().OnKeyRemove += OnRoomRemove;
        Singleton<RoomManager>.GetInstance().OnValueChanged += OnRoomModify;
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }
    // Update is called once per frame
    void Update()
    {
        if (addRooms.Count != 0)
        {
            AddRoom(addRooms.Dequeue());
        }

        if (rmRooms.Count != 0)
        {
            RmRoom(rmRooms.Dequeue());
        }
        if (modifyRooms.Count != 0)
        {
            ModifyRoom(modifyRooms.Dequeue());
        }
    }
    private void AddRoom(string roomId)
    {
        GameObject go = Instantiate(RoomPrefab);
        go.transform.SetParent(RoomParent,false);
        go.GetComponent<RoomListItem>().RoomData = Singleton<RoomManager>.GetInstance().GetRoom(roomId);
    }
    private void RmRoom(string roomId)
    {
        foreach (Transform transform in RoomParent)
        {
            if (transform.gameObject.GetComponent<RoomListItem>().RoomData.Id == roomId)
                Destroy(transform.gameObject);
        }
    }
    private void ModifyRoom(string roomId)
    {
        foreach (Transform transform in RoomParent)
        {
            if (transform.gameObject.GetComponent<RoomListItem>().RoomData.Id == roomId)
                transform.gameObject.GetComponent<RoomListItem>().RoomData = Singleton<RoomManager>.GetInstance().GetRoom(roomId);
        }
    }
    public void RequestRoomList()
    {
        Singleton<CommandSender>.GetInstance().SendControlCmd(Chat.Common.ControlType.GetRoomList);
    }
    private void OnRoomAdd(string roomId)
    {
        addRooms.Enqueue(roomId);
    }
    private void OnRoomRemove(string roomId)
    {
        rmRooms.Enqueue(roomId);
    }
    private void OnRoomModify(string roomId)
    {
        modifyRooms.Enqueue(roomId);
    }
}
